package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialBreakageDeliveryMaterialEntity;
import city.spring.modules.material.repository.MaterialBreakageDeliveryMaterialRepository;
import city.spring.modules.material.service.MaterialBreakageDeliveryMaterialService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：报损出库关联物资表
 *
 * @author 谢金婷
 * @date 2021-01-20 10:53:12
 */
@RestController
@RequestMapping("/material_breakage_delivery/{breakageId}/material")
public class MaterialBreakageDeliveryMaterialController extends ApiController {
    private final MaterialBreakageDeliveryMaterialService materialBreakageDeliveryMaterialService;
    private final MaterialBreakageDeliveryMaterialRepository materialBreakageDeliveryMaterialRepository;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialBreakageDeliveryMaterialEntity, ?>> entityOrderFields;

    public MaterialBreakageDeliveryMaterialController(MaterialBreakageDeliveryMaterialService materialBreakageDeliveryMaterialService, MaterialBreakageDeliveryMaterialRepository materialBreakageDeliveryMaterialRepository) {
        this.materialBreakageDeliveryMaterialService = materialBreakageDeliveryMaterialService;
        this.materialBreakageDeliveryMaterialRepository = materialBreakageDeliveryMaterialRepository;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getId);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getBreakageId);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getStorehouseId);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getMaterialId);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getBreakageQuantity);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getUnitmeasurement);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getUnitprice);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getBreakageTotal);
        entityOrderFields.add(MaterialBreakageDeliveryMaterialEntity::getReason);
    }

    @ModelAttribute
    public void getBreakageId(@PathVariable String breakageId) {
        if (breakageId == null) {
            throw new RuntimeException("报损出库单ID必须不为空");
        }
        System.out.println("breakageId" + breakageId);
    }

    /**
     * 获取全部的 <strong>报损出库关联物资表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MaterialBreakageDeliveryMaterialEntity entity) {
        LambdaQueryChainWrapper<MaterialBreakageDeliveryMaterialEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    //    /**
//     * 分页获取 <strong>报损出库关联物资表</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, MaterialBreakageDeliveryMaterialEntity entity) {
//        LambdaQueryChainWrapper<MaterialBreakageDeliveryMaterialEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MaterialBreakageDeliveryMaterialEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }
    @GetMapping
    public Object list(@PathVariable String breakageId) {
        return success(materialBreakageDeliveryMaterialRepository.getDeliveryMaterials(breakageId));
    }

    //    /**
//     * 获取一个 <strong>报损出库关联物资表</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(materialBreakageDeliveryMaterialService.getById(id));
//    }
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String breakageId, @PathVariable String extId) {
        return success(materialBreakageDeliveryMaterialRepository.getDeliveryMaterial(breakageId, extId));
    }

    //    /**
//     * 添加一个 <strong>报损出库关联物资表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody MaterialBreakageDeliveryMaterialEntity entity) {
//        materialBreakageDeliveryMaterialService.saveMaterialBreakageDeliveryMaterial(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }
    @PostMapping
    public Object addAll(@PathVariable String breakageId, @RequestBody List<MaterialBreakageDeliveryMaterialEntity> materials) {

        // 查出已有的数据
        List<MaterialBreakageDeliveryMaterialEntity> dbMaterials = materialBreakageDeliveryMaterialRepository.getDeliveryMaterials(breakageId);

        // 数据库已经存在的物资列表
        Set<String> dbMaterialIdsSet = dbMaterials.stream()
                .map(MaterialBreakageDeliveryMaterialEntity::getMaterialId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<MaterialBreakageDeliveryMaterialEntity> needSaveMaterials = materials.stream()
                .filter(item -> {
                    item.setBreakageId(breakageId);
                    item.setBreakageTotal(item.getBreakageQuantity().multiply(item.getUnitprice()));
                    String materialId = item.getMaterialId();
                    // 过滤出不存在数据库中的数据
                    return materialId != null && !dbMaterialIdsSet.contains(materialId);
                }).collect(Collectors.toList());

        if (!needSaveMaterials.isEmpty()) {
            materialBreakageDeliveryMaterialService.saveBatch(needSaveMaterials);
        }

        return success(null);
    }

    //    /**
//     * 修改一个 <strong>报损出库关联物资表</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody MaterialBreakageDeliveryMaterialEntity entity) {
//        entity.setId(id);
//        materialBreakageDeliveryMaterialService.updateMaterialBreakageDeliveryMaterial(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
    @PutMapping("{extId}")
    public Object update(@PathVariable String breakageId, @PathVariable String extId, @RequestBody MaterialBreakageDeliveryMaterialEntity extEntity) {
        extEntity.setId(extId);
        extEntity.setBreakageId(breakageId);
        materialBreakageDeliveryMaterialService.updateMaterialBreakageDeliveryMaterial(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>报损出库关联物资表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialBreakageDeliveryMaterialService.deleteMaterialBreakageDeliveryMaterial(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>报损出库关联物资表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialBreakageDeliveryMaterialService.deleteMaterialBreakageDeliveryMaterial(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialBreakageDeliveryMaterialEntity> buildLambdaQuery(MaterialBreakageDeliveryMaterialEntity entity) {
        LambdaQueryChainWrapper<MaterialBreakageDeliveryMaterialEntity> lambdaQuery = materialBreakageDeliveryMaterialService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MaterialBreakageDeliveryMaterialEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getBreakageId()), MaterialBreakageDeliveryMaterialEntity::getBreakageId, entity.getBreakageId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStorehouseId()), MaterialBreakageDeliveryMaterialEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMaterialId()), MaterialBreakageDeliveryMaterialEntity::getMaterialId, entity.getMaterialId());
        lambdaQuery.eq(entity.getBreakageQuantity() != null, MaterialBreakageDeliveryMaterialEntity::getBreakageQuantity, entity.getBreakageQuantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnitmeasurement()), MaterialBreakageDeliveryMaterialEntity::getUnitmeasurement, entity.getUnitmeasurement());
        lambdaQuery.eq(entity.getUnitprice() != null, MaterialBreakageDeliveryMaterialEntity::getUnitprice, entity.getUnitprice());
        lambdaQuery.eq(entity.getBreakageTotal() != null, MaterialBreakageDeliveryMaterialEntity::getBreakageTotal, entity.getBreakageTotal());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReason()), MaterialBreakageDeliveryMaterialEntity::getReason, entity.getReason());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialBreakageDeliveryMaterialEntity> buildQuery(MaterialBreakageDeliveryMaterialEntity entity) {
        QueryWrapper<MaterialBreakageDeliveryMaterialEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getBreakageId()), "breakage_id", entity.getBreakageId());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getMaterialId()), "material_id", entity.getMaterialId());
        wrapper.eq(entity.getBreakageQuantity() != null, "breakage_quantity", entity.getBreakageQuantity());
        wrapper.like(StringUtils.isNotBlank(entity.getUnitmeasurement()), "unitmeasurement", entity.getUnitmeasurement());
        wrapper.eq(entity.getUnitprice() != null, "unitprice", entity.getUnitprice());
        wrapper.eq(entity.getBreakageTotal() != null, "breakage_total", entity.getBreakageTotal());
        wrapper.like(StringUtils.isNotBlank(entity.getReason()), "reason", entity.getReason());
        return wrapper;
    }

}
